'use strict';
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  // 1. 解析请求体
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return { code: 400, msg: "请求体解析失败" };
    }
  }

  const { uniIdToken, day } = body;

  // 2. 验证token获取uid
  const uniIDIns = uniID.createInstance({ context });
  let uid;
  try {
    const tokenInfo = await uniIDIns.checkToken(uniIdToken);
    uid = tokenInfo.uid;
    if (!uid) {
      return { code: 403, msg: "身份验证失败" };
    }
  } catch (err) {
    return { code: 403, msg: "身份验证失败", error: err.message };
  }

  // 3. 参数存在性检查和格式校验
  if (!day) {
    return { code: 400, msg: "缺少必要的参数day" };
  }

  const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
  if (!dateRegex.test(day)) {
    return { code: 400, msg: "日期格式不正确，应为 YYYY-MM-DD 格式" };
  }

  const dateObj = new Date(day);
  if (isNaN(dateObj.getTime())) {
    return { code: 400, msg: "提供的日期无效" };
  }

  try {
    const db = uniCloud.database();
    const relationCollection = db.collection('sc_relations');

    // 查询当前咨询师的督导
    const relationRes = await relationCollection.where({
      consultant_id: uid
    }).get();

    if (!relationRes.data || relationRes.data.length === 0) {
      return {
        code: 404,
        msg: "未找到督导信息",
        data: {
          consultant_id: uid,
          supervisor: null
        }
      };
    }

    const supervisorId = relationRes.data[0].supervisor_id;

    // 查询该督导的排班
    const scheduleCollection = db.collection('consultant_schedule');
    const scheduleRes = await scheduleCollection
      .where({
        user: supervisorId,
        day: day
      })
      .get();

    const allFreeSlots = scheduleRes.data.flatMap(schedule => schedule.freeSlots || []);

    // 去重并排序
    const uniqueFreeSlots = [...new Set(allFreeSlots)].sort((a, b) => {
      const timeToMinutes = (timeStr) => {
        const [hours, minutes] = timeStr.split(':').map(Number);
        return hours * 60 + minutes;
      };
      const [startA] = a.split('-');
      const [startB] = b.split('-');
      return timeToMinutes(startA) - timeToMinutes(startB);
    });

    return {
      code: 0,
      msg: "查询成功",
      data: {
        consultant_id: uid,
        supervisor_id: supervisorId,
        schedules: uniqueFreeSlots
      }
    };

  } catch (e) {
    console.error("数据库查询异常:", e);
    return {
      code: 500,
      msg: "数据库查询失败",
      error: e.message
    };
  }
};
